package cn.tlb.ui.widget;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

import cn.tlb.xutilsdownload.R;

public class JSDemoActivity extends AppCompatActivity {
    private WebView webView;

    private JSDemoActivity jsDemoActivity;
    //@SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jsdemo);
        webView = (WebView)findViewById(R.id.webView);

        //设置允许java调用javascript脚本
        webView.getSettings().setJavaScriptEnabled(true);
        //不设置java无法调用js的alert弹窗
        webView.setWebChromeClient(new WebChromeClient());
        // api>=17开始, 与js交互的java方法必须为 public的且被@JavascriptInterface注解
        webView.addJavascriptInterface(this, "JSDemoActivity");
        // 加载assets文件夹下的html页面
        webView.loadUrl("file:///android_asset/index.html");

    }

    @JavascriptInterface
    public void showToast(String message){
        Toast.makeText(JSDemoActivity.this, message, Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public void callJSMethod(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("javascript:calledByActivity('"+str+"')");
            }
        });
    }

    // 调用js方法
    public void onclick(View view) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("javascript:calledByActivity('Hello world from Activity!')");
            }
        });
    }
}
